package com.fanben100.gui;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.KeyStroke;

import com.fanben100.biz.LoginTemplateFactory;
import com.fanben100.biz.LogonState;
import com.fanben100.biz.RegistContext;
import com.fanben100.biz.SystemState;
import com.fanben100.biz.ValidLoginModel;
import com.fanben100.domain.LoginModel;
import com.fanben100.domain.Operater;
import com.fanben100.domain.Seller;
import com.fanben100.domain.SysConfig;
import com.fanben100.gui.i18n.ResourceContext;
import com.fanben100.util.DialogUtil;
import com.fanben100.util.NumberUtil;
import com.fanben100.util.StringUtil;

public class UserLoginDialog extends JDialog {

	private ResourceContext rt = ResourceContext.getInstance("UserLoginDialog");
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private JLabel sellerIdLabel = null;
	private JTextField sellerIdField = null;

	private JLabel sellerPasswordLabel = null;
	private JPasswordField sellerPasswordField = null;

	private JLabel userTypeLabel = new JLabel("用户类型:");
	private JComboBox userTypeCombo = new JComboBox();

	private LoginModel loginModel = null;

	private JButton loginButton = new JButton(rt.getString("loginButton"));

	public UserLoginDialog(JFrame frame, boolean modal) {
		super(frame, "用户登录", modal);
		// this.setUndecorated(true);
		this.setSize(new Dimension(180, 100));
		this.setLocationRelativeTo(frame);
		// this.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
		this.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				dispose();
			}
		});
		try {
			jbInit();
			pack();
			// getContentPane().setSize(500, 400);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	// public UserLoginDialog() {
	// this(null, "用户登录", true);
	// }

	private void jbInit() throws Exception {
		this.setResizable(false);
		JPanel sellerRegistPanel = new JPanel(false);
		sellerRegistPanel.setLayout(new BoxLayout(sellerRegistPanel,
				BoxLayout.X_AXIS));

		sellerIdLabel = new JLabel(rt.getColonString("userNo"), JLabel.RIGHT);
		sellerIdField = new JTextField();
		sellerIdField.setColumns(15);
		sellerIdField.setSize(new Dimension(50, 10));

		sellerPasswordLabel = new JLabel(rt.getColonString("userPassword"),
				JLabel.RIGHT);
		sellerPasswordField = new JPasswordField();
		sellerPasswordField.setEchoChar('*');
		sellerPasswordField.setColumns(15);

		userTypeCombo.addItem(rt.getString("userTypeOperater"));
		userTypeCombo.addItem(rt.getString("userTypeSeller"));

		loginButton.registerKeyboardAction(new UserLoginAction(),
				KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0),
				JComponent.WHEN_IN_FOCUSED_WINDOW);
		loginButton.addActionListener(new UserLoginAction());
		// loginButton.setMnemonic(KeyEvent.VK_ENTER);
		// loginButton.set
		loginButton.setSize(new Dimension(20, 10));

		JPanel labelPanel = new JPanel(false);
		labelPanel.setLayout(new GridLayout(0, 1));
		labelPanel.add(sellerIdLabel);
		labelPanel.add(sellerPasswordLabel);
		labelPanel.add(userTypeLabel);

		JPanel fieldPanel = new JPanel(false);
		fieldPanel.setLayout(new GridLayout(0, 1));
		fieldPanel.add(sellerIdField);
		fieldPanel.add(sellerPasswordField);
		fieldPanel.add(userTypeCombo);

		getContentPane().setLayout(new BorderLayout());

		sellerRegistPanel.add(labelPanel);
		sellerRegistPanel.add(fieldPanel);
		this.getContentPane().add(sellerRegistPanel, BorderLayout.CENTER);
		this.getContentPane().add(loginButton, BorderLayout.PAGE_END);
		// getContentPane().setSize(new Dimension(500, 400));
	}

	@Override
	/**
	 * 重写该方法实现登录用户姓名设置
	 */
	public void dispose() {
		Container container = this.getParent(), root = container;
		while (container != null) {
			root = container;
			container = container.getParent();
			if (container instanceof TerminalFrame) {
				break;
			}
		}
		if (root != null && root instanceof TerminalFrame) {
			TerminalFrame frame = (TerminalFrame) root;
			if (loginModel != null) {
				frame.getLabOperaterContent().setText(loginModel.getRealName());
			}
		}
		super.dispose();
	}

	/**
	 * 重写该方法实现主窗体卸载
	 */
	@Override
	protected void processWindowEvent(WindowEvent e) {
		SystemState currentState = RegistContext.getInstance().getSysState();
		boolean currentLogon = currentState instanceof LogonState;
		// 如果当前登录状态为已登录，不强制退出系统
		if (e.getID() == WindowEvent.WINDOW_CLOSING && !currentLogon) {
			Container container = this.getParent(), root = container;
			while (container != null) {
				root = container;
				container = container.getParent();
				if (container instanceof TerminalFrame) {
					break;
				}
			}
			if (root != null && root instanceof TerminalFrame) {
				TerminalFrame frame = (TerminalFrame) root;
				frame.dispose();
				System.exit(0);
			}
		}
		super.processWindowEvent(e);
	}

	/**
	 * 用户登录Action
	 * 
	 * @author Administrator
	 * 
	 */
	private class UserLoginAction implements ActionListener, Runnable {
		public void actionPerformed(ActionEvent e) {
			// if (!NumberUtil.isNumeric1(sellerIdField.getText())) {
			// sellerIdField.setText("用户编号必须为数字。");
			// sellerIdField.selectAll();
			// return;
			// }
			if (StringUtil.isNullOrEmpty(sellerIdField.getText())) {
				sellerIdField.setText("必须输入用户编号");
				sellerIdField.selectAll();
				return;
			}
			if (sellerPasswordField.getPassword() == null
					|| sellerPasswordField.getPassword().length < 3) {
				sellerIdField.setText("必须输入用户密码，且密码位数必须大于三位");
				sellerIdField.selectAll();
				return;
			}
			loginButton.setEnabled(false);
			Thread loginThread = new Thread(this);
			loginThread.start();
		}

		public void run() {
			LoginModel loginModel = null;
			if (userTypeCombo.getSelectedItem().toString().replace(" ", "")
					.equals("商家")) {
				Seller seller = new Seller();
				seller.setIdentify(SysConfig.sellerLoginModel.getIdentify());
				loginModel = seller;
			}
			if (userTypeCombo.getSelectedItem().toString().replace(" ", "")
					.equals("收银员")) {
				loginModel = new Operater();
			}
			if (loginModel != null) {
				loginModel.setLoginId(sellerIdField.getText());
				StringBuffer passwordBuffer = new StringBuffer();
				for (char pc : sellerPasswordField.getPassword()) {
					passwordBuffer.append(pc);
				}
				loginModel.setLoginPassword(passwordBuffer.toString());
			}
			// loginModel.setLoginId(NumberUtil.tryParseInt(sellerIdField
			// .getText()));
			// loginModel.setLoginPassword(sellerPasswordField.getText());

			ValidLoginModel validModel = LoginTemplateFactory.getLoginTemplate(
					loginModel).directLogin(loginModel);
			if (validModel != null && validModel.isValid()) {
				UserLoginDialog.this.loginModel = loginModel;
				UserLoginDialog.this.dispose();

				TerminalFrame terminalFrame = (TerminalFrame) DialogUtil
						.getModalFrame(UserLoginDialog.this);

				terminalFrame.resetContentPanel();
				terminalFrame.getContentPane().setVisible(true);
				terminalFrame.setConnectOperater(validModel);
				terminalFrame.getLabOperaterContent().setText(
						String.valueOf(validModel.getRealName()));
				ValidLoginModel sellerContextModel = (ValidLoginModel) SysConfig.sellerLoginModel;
				Integer sellerId = 0;
				if (sellerContextModel != null
						&& sellerContextModel.getLoginModel() != null
						&& sellerContextModel.getLoginModel() instanceof Seller) {
					Seller seller = (Seller) sellerContextModel.getLoginModel();
					sellerId = seller.getSellerId();
				}
				terminalFrame.getLabSellerNoContent().setText(
						String.valueOf(sellerId));
				terminalFrame.getLabSellerNameContent().setText(
						SysConfig.sellerLoginModel.getRealName());
				terminalFrame.getTxtExpenditure().grabFocus();
				RegistContext.getInstance().setSysState(new LogonState(),
						terminalFrame);
			} else {
				JOptionPane.showMessageDialog(UserLoginDialog.this, "登录失败，"
						+ validModel != null ? validModel.getValidMessage()
						: "发送验证请求失败，服务器无响应", "错误", JOptionPane.ERROR_MESSAGE);
			}
			loginButton.setEnabled(true);
		}
	}
}
